package com.aitaoxue.palx.im.message;

import io.rong.common.ParcelUtils;
import io.rong.imlib.MessageTag;
import io.rong.imlib.model.MessageContent;

import java.io.UnsupportedEncodingException;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Parcel;
import android.text.TextUtils;

@MessageTag(value = "RC:PUSH_MESSAGE")
public class PushMessage extends MessageContent {

	private String content;
	private int extra;

	protected PushMessage() {

	}

	public PushMessage(Parcel in) {
		setContent(ParcelUtils.readFromParcel(in));
		setExtra(ParcelUtils.readIntFromParcel(in));
	}

	public PushMessage(byte[] data) {
		String jsonStr = null;

		try {
			jsonStr = new String(data, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		try {
			JSONObject jsonObj = new JSONObject(jsonStr);

			if (jsonObj.has("content")) {
				setContent(jsonObj.getString("content"));
			}
			if (jsonObj.has("extra")) {
				setExtra(jsonObj.getInt("extra"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static PushMessage obtain(String text, int type) {
		PushMessage model = new PushMessage();

		model.setContent(text);
		model.setExtra(type);

		return model;
	}

	@Override
	public int describeContents() {
		return 0;
	}

	public byte[] encode() {
		JSONObject json = new JSONObject();

		try {
			json.put("content", getContent());

			json.put("extra", getExtra());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		try {
			return json.toString().getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		ParcelUtils.writeToParcel(dest, content);
		ParcelUtils.writeToParcel(dest, getExtra());
	}

	public static Creator<PushMessage> CREATOR = new Creator<PushMessage>() {

		@Override
		public PushMessage createFromParcel(Parcel source) {
			return new PushMessage(source);
		}

		@Override
		public PushMessage[] newArray(int size) {
			return new PushMessage[size];
		}

	};

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public int getExtra() {
		return extra;
	}

	public void setExtra(int extra) {
		this.extra = extra;
	}

}
